import shlex
import re

TYPE_SPECIFIERS = ["int","char","float","double"]
Identifier = re.compile("[a-zA-Z][a-zA-Z0-9_]*")

class Lexer:
    def __init__(self,filename):
        self.lexer = shlex.shlex(open(filename,"r"))
        self.lexer.wordchars += "A-Za-z0-9_"
        self.curr_token = None

    def next(self):
        self.curr_token = self.lexer.get_token()
        return self.curr_token

    def putback(self,token=None):
        if token == None:
            self.lexer.push_token(self.curr_token)
        else:
            self.lexer.push_token(token)


def parseTypeSpecifier(lexer):
    token = lexer.next()

    if token in TYPE_SPECIFIERS:
        return True
    if token == "struct":
        if lexer.next() == '{':
            parseTypeDeclList(lexer)
            if lexer.next() == '}':
                return True
        else:
            parseIdentifier()
            if lexer.next() == '{':
                parseTypeDeclList(lexer)
                if lexer.next() == '}':
                    return True
            else:
                return False
        
def parseTypeDeclList(lexer):
    res=parseTypeDeclaration(lexer)
    if not res:
        return  parseTypeDeclaration(lexer) and parseTypeDeclList(lexer)
    else:
        return res

def parseIdentifier(lexer):
    return Identifier.match(lexer.next())

def parseDeclaratorList(lexer):
    if parseIdentifier(lexer):
        return True
    else:
        if lexer.next() == '*' and parseIdentifier(lexer):
            return True
        
def parseTypeDeclaration(lexer):
    res = parseTypeSpecifier(lexer)
    print 'pTS',res
    dlist = parseDeclaratorList(lexer)
    print 'dlist',dlist
    return res and dlist
            
def main():    
    l = Lexer('struct.c')
    print parseTypeDeclList(l)

    
if __name__=='__main__':
    main()


